/****************************************************************************

 Copyright (C) 2002-2011 Gilles Debunne. All rights reserved.

 This file is part of the QGLViewer library version 2.3.17.

 http://www.libqglviewer.com - contact@libqglviewer.com

 This file may be used under the terms of the GNU General Public License
 versions 2.0 or 3.0 as published by the Free Software Foundation and
 appearing in the LICENSE file included in the packaging of this file.
 In addition, as a special exception, Gilles Debunne gives you certain
 additional rights, described in the file GPL_EXCEPTION in this package.

 libQGLViewer uses dual licensing. Commercial/proprietary software must
 purchase a libQGLViewer Commercial License.

 This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
 WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.

*****************************************************************************/

#include "viewer.h"
#include "camera.h"
#include "display.h"
#include "scene.h"
#include <qmessagebox.h>
#include "typedefs.h"
#include "angleaxis.h"
#include "TriMesh.h"


#if QT_VERSION >= 0x040000
# include <QKeyEvent>
#endif

using namespace std;
using namespace qglviewer;

Viewer::Viewer(StandardCamera* nfc)
{
    // Change the camera.
    Camera* c = camera();
    setCamera(nfc);
    delete c;

    scene = new Scene();
    display = new Display(scene);
    qglviewer::Vec m1(scene->aabb.min().x(),scene->aabb.min().y(),scene->aabb.min().z());
    qglviewer::Vec m2(scene->aabb.max().x(),scene->aabb.max().y(),scene->aabb.max().z());
    this->setSceneBoundingBox(m1,m2);

    simulationTimer = new QTimer( );
    connect( simulationTimer, SIGNAL(timeout()), this, SLOT(animate()) );
    simulationTimer->start(1);

    drawProfile = true;
}

void Viewer::draw()
{

    // ModelView represents the world coordinate system at the beginning of draw()
    // Place light at camera position
    const Vec cameraPos = camera()->position();
    const GLfloat pos[4] = {cameraPos[0], cameraPos[1], cameraPos[2], 1.0};
    glLightfv(GL_LIGHT1, GL_POSITION, pos);
    // Orientate light along view direction
    glLightfv(GL_LIGHT1, GL_SPOT_DIRECTION, camera()->viewDirection());
    //glDisable(GL_LIGHTING);

    display->draw(false);
    //((BulletRigidBodyEngine*) scene->engine)->displayCallback();

    if(drawProfile)
    {
        //glDisable(GL_LIGHTING);
        std::stringstream ss;
        ss << "Physics time in milliseconds: " << scene->timePhysics;
        glColor3f(1,1,1);
        drawText(15,20,ss.str().c_str());
        //glEnable(GL_LIGHTING);
    }

    if(gridIsDrawn())
        drawGrid(10,20);
    if(axisIsDrawn())
        drawAxis(10);

}

void Viewer::setSolid() { display->SetFill();  }
void Viewer::setWire() { display->SetWire();  }

void Viewer::init()
{
    // Light setup
    glDisable(GL_LIGHT0);
    glEnable(GL_LIGHT1);

    // Light default parameters
    const GLfloat light_ambient[4]  = {1.0, 1.0, 1.0, 1.0};
    const GLfloat light_specular[4] = {1.0, 1.0, 1.0, 1.0};
    const GLfloat light_diffuse[4]  = {1.0, 1.0, 1.0, 1.0};

//    glLightf( GL_LIGHT1, GL_SPOT_EXPONENT, 1.0);
//    glLightf( GL_LIGHT1, GL_SPOT_CUTOFF,   25.0);
    glLightf( GL_LIGHT1, GL_CONSTANT_ATTENUATION,  0.1f);
    glLightf( GL_LIGHT1, GL_LINEAR_ATTENUATION,    0.01f);
    glLightf( GL_LIGHT1, GL_QUADRATIC_ATTENUATION, 0.001f);
    glLightfv(GL_LIGHT1, GL_AMBIENT,  light_ambient);
    glLightfv(GL_LIGHT1, GL_SPECULAR, light_specular);
    glLightfv(GL_LIGHT1, GL_DIFFUSE,  light_diffuse);

    glShadeModel(GL_SMOOTH);
    glEnable(GL_CULL_FACE);

    if(display->useMaterial)
        glDisable(GL_COLOR_MATERIAL);
    else
        glDisable(GL_LIGHTING);
    // Restore previous viewer state.
    if (!restoreStateFromFile())
        showEntireScene();

    setKeyDescription(Qt::Key_T, "Toggles camera type (perspective or orthographic)");
    setKeyDescription(Qt::Key_M, "Toggles camera mode (standard or QGLViewer)");

    setMouseBindingDescription(Qt::SHIFT + Qt::MidButton, "Change frustum size (for standard camera in orthographic mode)");

    // Display help window.
    //help();

}

void Viewer::showMessage()
{
    QString std = ((StandardCamera*)camera())->isStandard()?"Standard camera":"QGLViewer camera";
    QString type = camera()->type() == Camera::PERSPECTIVE?"Perspective":"Orthographic";
    displayMessage(std + " - " + type);
    Q_EMIT cameraChanged();
}

void Viewer::keyPressEvent(QKeyEvent *e)
{
    switch(e->key()){
    case Qt::Key_M:
        // 'M' changes mode : standard or QGLViewer camera
        ((StandardCamera*)camera())->toggleMode();
        showMessage();
        break;

    case Qt::Key_T:
        // 'T' changes the projection type : perspective or orthogonal
        if (camera()->type() == Camera::ORTHOGRAPHIC)
            camera()->setType(Camera::PERSPECTIVE);
        else
            camera()->setType(Camera::ORTHOGRAPHIC);
        showMessage();
        break;

    case Qt::Key_Delete:
        if(scene->selectedBody)
            scene->removeSelectedBody();
        break;

    default:
        QGLViewer::keyPressEvent(e);
        break;
    }
}

void Viewer::wheelEvent(QWheelEvent *e)
{
    if ((camera()->type() == Camera::ORTHOGRAPHIC) && (((StandardCamera*)camera())->isStandard()) &&
        #if QT_VERSION >= 0x040000
            (e->modifiers() & Qt::ShiftModifier))
#else
            (e->state() & Qt::ShiftButton))
#endif
    {
        ((StandardCamera*)camera())->changeOrthoFrustumSize(e->delta());
        Q_EMIT cameraChanged();
        updateGL();
    }
    else
        QGLViewer::wheelEvent(e);
}

QString Viewer::helpString() const
{
    QString text("<h2>S t a n d a r d C a m e r a</h2>");
    text += "An overloaded <code>Camera</code> class is used, that reproduces the 'standard' OpenGL settings.<br><br>";

    text += "With this camera, the near and (resp. far) plane distance is set to a very small (resp. very large) value. ";
    text += "With the orthographic camera type, the frustum dimensions are fixed. Use <code>Shift</code> and the mouse wheel to change them.<br><br>";

    text += "On the other hand, the QGLViewer camera fits the near and far distances to the scene radius. ";
    text += "Fine tuning is available using <code>zClippingCoefficient()</code> and <code>zNearCoefficient()</code>. ";
    text += "However, visual results do not seem to be impacted by this zBuffer fitted range.<br><br>";
    text += "The QGLViewer camera also adapts the orthographic frustum dimensions to the distance to the <code>revolveAroundPoint()</code> to mimic a perspective camera. ";
    text += "Since this behavior may not be needed, this example shows how to override it.<br><br>";

    text += "The second viewer displays the first one's camera to show its configuration.<br><br>";

    text += "Use <b>M</b> to switch between 'standard' and QGLViewer camera behavior.<br>";
    text += "Use <b>T</b> to switch between perspective and orthographic camera type.<br><br>";

    text += "Use <b>Shift+wheel</b> to change standard camera orthographic size.";

    return text;
}

void Viewer::animate()
{
    scene->simulate();
    simulationTimer->start(1);
    this->update();
}

void Viewer::setPlay()
{
    scene->engine->pause = !scene->engine->pause;
}

void Viewer::stop()
{
    scene->stop();
}

void Viewer::saveScene()
{
    scene->save();
}

void Viewer::loadScene()
{
    scene->load();
    emit gravityChanged(QString::number(scene->engine->gravity));
    emit timestepChanged(QString::number(scene->engine->timestep));
    selectedChanged();
    updateGL();
}

void Viewer::deleteScene()
{
    scene->deleteScene();
}

void Viewer::drawWithNames()
{
    display->draw(true);

}

void Viewer::postSelection(const QPoint& point)
{
    // Compute orig and dir, used to draw a representation of the intersecting line
    camera()->convertClickToLine(point, orig, dir);

    // Find the selectedPoint coordinates, using camera()->pointUnderPixel().
    bool found;
    selectedPoint = camera()->pointUnderPixel(point, found);
    selectedPoint -= 0.01f*dir; // Small offset to make point clearly visible.
    // Note that "found" is different from (selectedObjectId()>=0) because of the size of the select region.

    if (selectedName() == -1)
        scene->selectedBody = NULL;
    else
    {
        scene->selectBody(selectedName());
    }
    selectedChanged();
}

void Viewer::addSphere(Math::Real radius)
{
    Math::Vector3 t(0,0,0);
    scene->createSphere(radius,t);

}

void Viewer::addBox(Math::Vector3 &sizeBox)
{
    Math::Vector3 t(0,0,0);
    Math::Quaternion r = Math::Quaternion::IDENTITY;
    scene->createBox(sizeBox,t,r);
}

void Viewer::addMesh(QString filename)
{
    Math::Vector3 t(0,0,0);
    Math::Quaternion r = Math::Quaternion::IDENTITY;
    scene->createMesh(filename,t,r);
}

void Viewer::setSelectedBBox(int val)
{
    if(val)
        display->showBBox = true;
    else
        display->showBBox = false;

}

void Viewer::setSelectedColor(QColor cd)
{
    if(scene->selectedBody)
        scene->selectedBody->color = cd;
}

void Viewer::focusSelected()
{
    if(scene->selectedBody)
    {
        Math::Vector3 c = scene->selectedBody->aabb.getCenter();
        Vec center(c.x(),c.y(),c.z());
        this->camera()->lookAt(center);
    }
}

void Viewer::translateSelected(Math::Vector3 &t)
{
    if(scene->selectedBody)
    {
        scene->selectedBody->initPosition = scene->selectedBody->position = t;
        scene->engine->translateBody(scene->selectedBody,t);
    }
}

void Viewer::rotateSelected(Math::Real &angle, Math::Vector3 &t)
{
    if(scene->selectedBody)
    {
        scene->selectedBody->initOrientation = scene->selectedBody->orientation = Math::Quaternion(Math::AngleAxis(angle,t));
    }
}

void Viewer::setGravity(Math::Real &g)
{
    scene->engine->setGravity(g);
}

void Viewer::setSelectedStatic(int &s)
{
    if(scene->selectedBody)
    {
        scene->engine->setStatic(scene->selectedBody,s);
        scene->selectedBody->isStatic = s;
    }
}

void Viewer::selectedChanged()
{
    if(scene->selectedBody)
        emit selectedPositionChanged(scene->selectedBody->position);
}
